<?php

include 'confidential_settings.php';
// This include contains 5 variables:
//  - db_name: database name
//  - table_name_x: table name
//  - username: username
//  - password: password
//  - localhost: host name

function get_corr_value_month($year,$month){
	include 'gsc_corrections.php';

	$ret_corr_value = 0;
	for($i=0;$i<count($corr_year);$i++){
		if((trim($corr_year[$i]) == trim($year))&&(trim($corr_month[$i]) == trim($month))){
			$ret_corr_value = $ret_corr_value + $corr_value[$i];
		}
	}
	return $ret_corr_value;
}


$dbh=mysql_connect ($localhost, $username, $password) or die('Cannot connect to the database because: ' . mysql_error());

mysql_select_db ($db_name) or die(mysql_error()); 

$result = mysql_query("SELECT YEAR(date_entered), MONTH(date_entered), MONTHNAME(date_entered), SUM(val) FROM $table_name_gsc WHERE DATE_SUB(CURDATE(),INTERVAL 15 MONTH) <= DATE(date_entered) GROUP BY YEAR(date_entered), MONTH(date_entered)");

mysql_close($dbh);


mysql_data_seek ($result , 0);

$max = 0;
$nb = 0;
while($row = mysql_fetch_array($result)){
	$corr_value_tmp = get_corr_value_month($row['YEAR(date_entered)'],$row['MONTH(date_entered)']);
	$tmp = $row['SUM(val)'];
	$tmp = ($tmp/1000) + ($corr_value_tmp);
	if($tmp > $max){
		$max = $tmp;
	}
	$nb = $nb + 1;
}
$max = $max * 1.05;

mysql_data_seek ($result , 0);

/*
echo "<br /><br />Values per month:<br />";
while($row = mysql_fetch_array($result)){
	echo $row['SUM(val)'] . " - " . $row['MONTHNAME(date_entered)'] . "  " . $row['YEAR(date_entered)'];
	echo "<br />";
}
*/

echo '<img src="http://chart.apis.google.com/chart?cht=bvs&chd=t:';
if($row = mysql_fetch_array($result)){
	$corr_value_tmp = get_corr_value_month($row['YEAR(date_entered)'],$row['MONTH(date_entered)']);
	$tmp = $row['SUM(val)'];
	$tmp = $tmp + (1000*$corr_value_tmp);
	$tmp = $tmp*100/$max/1000;
	echo $tmp;
}
while($row = mysql_fetch_array($result)){
	$corr_value_tmp = get_corr_value_month($row['YEAR(date_entered)'],$row['MONTH(date_entered)']);
	$tmp = $row['SUM(val)'];
	$tmp = $tmp + (1000*$corr_value_tmp);
	$tmp = $tmp*100/$max/1000;
	echo ',';
	echo $tmp;
}
echo '&chs=600x300&chg=20,20&chxt=x,y,x&chxr=1,0,';
echo $nb;
echo '|1,0,';
echo $max;

mysql_data_seek ($result , 0);

echo '&chxl=0:|';
while($row = mysql_fetch_array($result)){
	$tmp_month_name = $row['MONTHNAME(date_entered)'];
	echo substr($tmp_month_name, 0, 3);
	echo '|';
}

mysql_data_seek ($result , 0);

$prev_year = 0;
echo '2:|';
while($row = mysql_fetch_array($result)){
	if($prev_year <> $row['YEAR(date_entered)']){
		echo $row['YEAR(date_entered)'];
		$prev_year = $row['YEAR(date_entered)'];
	}
	echo '|';
}

echo '" />';

?>
